package model

import (
	"gorm.io/gorm/clause"
	"server/common"
)

type CaseMeau struct {
	Model

	Md5  string `gorm:"column:md5;type:varchar(32)" json:"md5"`
	Name string `gorm:"column:name;not null;type:varchar(100);" json:"name"`

	FatherMD5 *string `json:"father_md5"`

	ProjectID int     `json:"project_id"`
	Project   Project `gorm:"references:ID"`

	FatherID *uint      `gorm:"column:father" json:"father"`
	Childs   []CaseMeau `gorm:"foreignkey:FatherID" json:"childs"` //自引用has Many
}

func (meau *CaseMeau) TableName() string {
	return "case_meau"
}

func (meau *CaseMeau) List() []CaseMeau {
	var meau_list []CaseMeau
	if err := common.DB.Debug().Model(&CaseMeau{}).Preload(clause.Associations).Where("father is NULL").Find(&meau_list).Error; err != nil {
		return meau_list
	}
	return meau_list
}

func (meau *CaseMeau) Create() error {
	if err := common.DB.Debug().Omit("Childs").Create(&meau).Error; err != nil {
		return err
	}
	return nil
}

func (meau *CaseMeau) Update() error {
	if err := common.DB.Omit(clause.Associations).Where("id = ?", meau.ID).Updates(&meau).Error; err != nil {
		return err
	}
	return nil
}

func (meau *CaseMeau) Delete() error {
	if err := common.DB.Where("id = ?", meau.ID).Delete(&meau).Error; err != nil {
		return err
	}
	return nil
}

func (meau *CaseMeau) QueryById(id string) []CaseMeau {
	meau_list := []CaseMeau{}
	if err := common.DB.Debug().Model(&CaseMeau{}).Preload(clause.Associations).Where("father = ?", id).Find(&meau_list).Error; err != nil {
		return meau_list
	}
	return meau_list
}

func (meau *CaseMeau) QueryMd5(id string) {
	if err := common.DB.Model(&CaseMeau{}).Where("md5 = ?", id).First(&meau).Error; err != nil {
		return
	}
	return
}

func GetAllCaseMeau() []CaseMeau {
	meau_list := []CaseMeau{}
	if err := common.DB.Model(&CaseMeau{}).Find(&meau_list).Error; err != nil {
		return meau_list
	}
	return meau_list
}
